<script setup>
import { onMounted, onUnmounted, defineExpose, inject, defineEmits } from 'vue'
import EchartsController from './EchartsController';
import { useDataStore } from '@/store';

const emits = defineEmits(['mode-changed']);

const echartsInstance = new EchartsController();
const dataStore = useDataStore();

onMounted(() => {
	let dom = document.getElementById('canvas-container');

	echartsInstance.init({
		dom,
		config: {}
	});

	// 监听画点事件
	echartsInstance.on('point-added', (pointData) => {
		console.log('新增点位:', pointData);

		// 将新点位添加到数据存储中
		const newPoint = {
			x: pointData.x,
			y: pointData.y,
			name: `点位_${Date.now()}` // 生成唯一名称
		};

		// 使用新的方法添加点位
		dataStore.addCoordinatePoint(newPoint);

		// 验证图形元素是否正确添加
		console.log('当前图形元素数量:', echartsInstance.getGraphicCount());

		// 不要重新更新图表数据，因为图形元素已经在画布上显示了
		// echartsInstance.updateEchartsData(dataStore.roomList);
	});

	echartsInstance.on('contextmenu', (currentMode) => {
		if (currentMode !== 'preview') {
			echartsInstance.changeMode('preview');
			emits('mode-changed', 'preview');
		}
	});

	// 监听键盘事件 - ESC键退出编辑模式
	const handleKeyDown = (event) => {
		if (event.key === 'Escape') {
			// 退出编辑模式，回到预览模式
			echartsInstance.changeMode('preview');
			console.log('ESC键退出编辑模式');

			// 触发事件通知父组件更新工具栏状态
			emits('mode-changed', 'preview');
		}
	};

	document.addEventListener('keydown', handleKeyDown);

	// 在组件卸载时移除事件监听器
	onUnmounted(() => {
		document.removeEventListener('keydown', handleKeyDown);
	});
});

onUnmounted(() => {
	echartsInstance.dispose();
});

defineExpose({
	captureChart: echartsInstance.captureChart.bind(echartsInstance),
	updateEchartsData: echartsInstance.updateEchartsData.bind(echartsInstance),
	clearCanvas: echartsInstance.clearCanvas.bind(echartsInstance),
	changeMode: echartsInstance.changeMode.bind(echartsInstance),
	biggerPoint: echartsInstance.biggerPoint.bind(echartsInstance),
	resetToOriginalData: echartsInstance.resetToOriginalData.bind(echartsInstance),
	updateGraphicPositions: echartsInstance.updateGraphicPositions.bind(echartsInstance),
	getGraphicCount: echartsInstance.getGraphicCount.bind(echartsInstance)
});

</script>

<template>
	<div id="canvas-container"></div>
</template>

<style lang="scss" scoped>
#canvas-container {
	position: absolute;
	left: 301px;
	top: 30px;
	width: calc(100% - 301px);
	height: 100%;
	background-color: #fff;
	box-sizing: border-box;
	padding: 0px;
}
</style>